package plus.easydo.starter.oauth.server.service;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import plus.easydo.starter.oauth.core.model.CustomizeUserDetails;
import plus.easydo.starter.oauth.server.properties.Oauth2ServerProperties;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;


/**
 * 自定义令牌转换器 实现控制checkToken请求是否返回所有授权信息
 *
 * @author yuzhanfeng
 */
public class CustomizeDefaultUserAuthenticationConverter extends DefaultUserAuthenticationConverter implements UserAuthenticationConverter {

    private final Oauth2ServerProperties oauth2ServerProperties;

    public CustomizeDefaultUserAuthenticationConverter(Oauth2ServerProperties oauth2ServerProperties) {
        this.oauth2ServerProperties = oauth2ServerProperties;
    }

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        LinkedHashMap<String, Object> response = new LinkedHashMap<>();
        response.put("user_name", authentication.getName());
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        if (oauth2ServerProperties.isTokenInfoUser()) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof CustomizeUserDetails) {
                CustomizeUserDetails<?> myUserDetails = (CustomizeUserDetails<?>) principal;
                response.put("user", myUserDetails.getUser());
                response.put("permissions", myUserDetails.getPermissions());
            }
        }
        if (oauth2ServerProperties.isTokenInfoAll()) {
            response.put("ALL", authentication);
        }
        return response;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        CustomizeDefaultUserAuthenticationConverter that = (CustomizeDefaultUserAuthenticationConverter) o;
        return Objects.equals(oauth2ServerProperties, that.oauth2ServerProperties);
    }

    @Override
    public int hashCode() {
        return Objects.hash(oauth2ServerProperties);
    }
}
